/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.model.codes;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.zhiqim.kernel.constants.CodeConstants;
import org.zhiqim.kernel.model.results.RE;
import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Hexs;

/**
 * DES/ECB/NoPadding加解密
 *
 * @version v8.0.1 @author zouzhigang 2022年11月12日 新建与整理
 */
public class DESECBZero implements CodeConstants
{
    /** 加密 */
    public static RE<String> encrypt(String src, String key)
    {
        try
        {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(_DES_);
            SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(key.getBytes()));
            Cipher cipher = Cipher.getInstance(_DES_ECB_ZEROPADDING_);
            cipher.init(Cipher.ENCRYPT_MODE, securekey, new SecureRandom());
            byte[] dst = cipher.doFinal(pad8(src.getBytes()));
        
            return RE.value(Hexs.toHexString(dst));
        }
        catch(Exception e)
        {
            return RE.error(e);
        }
    }
    
    /** 解密 */
    public static RE<String> decrypt(String src, String key)
    {
        try
        {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(_DES_);
            SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(key.getBytes()));
            Cipher cipher = Cipher.getInstance(_DES_ECB_ZEROPADDING_);
            cipher.init(Cipher.DECRYPT_MODE, securekey, new SecureRandom());
            byte[] dst = cipher.doFinal(Hexs.toBytes(src));
            
            return RE.value(new String(dst, 0, padl(dst)));
        }
        catch(Exception e)
        {
            return RE.error(e);
        }
    }
    
    /** 补齐8位 */
    public static byte[] pad8(byte[] data)
    {
        int mod = data.length % 8;
        if (mod == 0)
            return data;
        
        byte[] newData = new byte[data.length + (8-mod)];
        Bytes.putBytes(newData, 0, data);
        
        return newData;
    }
    
    /** 有效长度 */
    public static int padl(byte[] data)
    {
        for (int i=data.length-1;i>=0;i--)
        {
            if (data[i] != (byte)0)
                return i+1;
        }
        
        return data.length;
    }
}
